// 对对碰
class DdpScene extends Scene {
    private cardGrp: eui.Group;
    private soundRight: egret.Sound;
    private soundWrong: egret.Sound;

    public constructor() {
        super();
        this.addEventListener(Events.ResourceLoadReady, this.created, this);
        this.init('DdpSceneSkin');
        this.loadSound();
    }

    private created(): void {
        const { stageWidth, stageHeight } = this.stage;
        const bg = new egret.Shape();
        const matrix = new egret.Matrix();
        matrix.createGradientBox(stageWidth, stageHeight);
        bg.graphics.beginGradientFill(
            egret.GradientType.RADIAL,
            GradientColorsBlue,
            [1, 1],
            [0, 255],
            matrix
        );
        bg.graphics.drawRect(0, 0, stageWidth, stageHeight);
        bg.graphics.endFill();
        this.addToBack(bg);

        drawBackBtn(this.frontLayer, Dispatcher.showMain);

        this.initCardGroup();
    }

    private loadSound(): void {
        const soundRight: egret.Sound = this.soundRight = new egret.Sound();
        const soundWrong: egret.Sound = this.soundWrong = new egret.Sound();
        soundRight.load("resource/sounds/score.mp3");
        soundWrong.load("resource/sounds/wrong.mp3");
    }

    private getNnArr(num2: number) {
        const numArr = [];
        while (numArr.length < num2) {
            const rn = randomNum(num2 - 1);
            if (numArr.indexOf(rn) === -1) {
                numArr.push(rn);
            }
        }
        const nnArr = [];
        numArr.map((num) => {
            const nn = Math.floor(num / 2);
            nnArr.push(nn);
        });
        return nnArr;
    }

    private drawOnCardGroup(colNum: number, rowNum: number): void {
        const cardGrp = this.cardGrp;
        cardGrp.removeChildren();

        const total = colNum * rowNum;
        const gapX = 20;
        const gapY = 20;
        const spWt = (cardGrp.width - gapX * (colNum - 1)) / colNum;
        const spHt = (cardGrp.height - gapY * (rowNum - 1)) / rowNum;

        const offsetX = spWt * 0.5;
        const nnArr = this.getNnArr(total);

        const sprMap = {};

        let clickGroup = [];

        const drawFront = (n: number) => {
            const sprData = sprMap[n];
            const spr: egret.Sprite = sprData.spr;
            const val: number = sprData.val;
            sprData.faceFlag = true;
            spr.removeChildren();
            const sp: egret.Shape = new egret.Shape();
            sp.graphics.beginFill(ColorWhite);
            sp.graphics.drawRect(0, 0, spWt, spHt);
            sp.graphics.endFill();
            sp.anchorOffsetX = offsetX;
            spr.addChild(sp);

            const bgArr = ['dw_hm', 'dw_dx', 'dw_hz', 'dw_bm', 'dw_cjl', 'dw_ls'];

            const wfBg = createBitmapByName(bgArr[val % bgArr.length]);
            const fw = spHt * 0.6;
            wfBg.x = (spWt - fw) * 0.5;
            wfBg.y = (spHt - fw) * 0.5;
            wfBg.width = fw;
            wfBg.height = fw;
            wfBg.anchorOffsetX = offsetX;
            spr.addChild(wfBg);

            const tx: egret.TextField = new egret.TextField();
            tx.x = 0;
            tx.y = 0;
            tx.text = val + '';
            tx.textColor = ColorBlack;
            spr.addChild(tx);
        };

        const drawBack = (n: number) => {
            const sprData = sprMap[n];
            const spr: egret.Sprite = sprData.spr;
            sprData.faceFlag = false;
            spr.removeChildren();
            const wfBg01 = createBitmapByName('wf_bg_01');
            wfBg01.width = spWt;
            wfBg01.height = spHt;
            wfBg01.anchorOffsetX = offsetX;
            spr.addChild(wfBg01);
        };

        const drawSuccessFlag = (n: number) => {
            const sprData = sprMap[n];
            const spr: egret.Sprite = sprData.spr;
            const sf: egret.Shape = new egret.Shape();
            sf.width = spWt;
            sf.height = spHt;
            sf.anchorOffsetX = offsetX;
            sf.graphics.lineStyle(5, ColorGreen, 0.5);
            sf.graphics.moveTo(0, 0);
            sf.graphics.lineTo(spWt, 0);
            sf.graphics.lineTo(spWt, spHt);
            sf.graphics.lineTo(0, spHt);
            sf.graphics.lineTo(0, 0);
            sf.graphics.endFill();
            spr.addChild(sf);
        };

        const playAnimation = (n: number, callback = null) => {
            const sprData = sprMap[n];
            const spr: egret.Sprite = sprData.spr;
            const faceFlag: boolean = sprData.faceFlag;
            egret.Tween.get(spr).to({ scaleX: 0 }, 300, egret.Ease.backIn).call(
                () => {
                    if (faceFlag) {
                        drawBack(n);
                    } else {
                        drawFront(n);
                    }
                    egret.Tween.get(spr).to({ scaleX: 1 }, 300, egret.Ease.backOut).call(
                        () => {
                            if (typeof callback === 'function') {
                                callback.call(null);
                            }
                        }
                    );
                }
            );
        };

        const manage2Card = (n: number) => {
            const sprData = sprMap[n];
            const right: number = sprData.right;
            const faceFlag: boolean = sprData.faceFlag; // 点击之前的面，true正，false反
            if (right === 0) {
                const len = clickGroup.length;
                if (len === 0) {
                    if (faceFlag) {
                        // 之前为正面，现为反面
                        // 异常处理
                    } else {
                        // 之前为反面，现为正面
                        clickGroup[0] = n;
                        playAnimation(n);
                    }
                } else if (len === 1) {
                    const an = clickGroup[0];
                    if (faceFlag) {
                        // 之前为正面，现为反面
                        if (an === n) {
                            clickGroup = [];
                            playAnimation(n);
                        } else {
                            // 异常处理
                        }
                    } else {
                        // 之前为反面，现为正面
                        if (an === n) {
                            // 异常处理，不应该出现
                        } else {
                            const aData = sprMap[an];
                            const nData = sprMap[n];
                            if (aData.val === nData.val) {
                                aData.right = 1;
                                nData.right = 1;
                                clickGroup = [];
                                this.soundRight.play(0, 1);
                                playAnimation(n, () => {
                                    drawSuccessFlag(an);
                                    drawSuccessFlag(n);
                                });
                            } else {
                                clickGroup = [];
                                playAnimation(n, () => {
                                    this.soundWrong.play(0, 1);
                                    playAnimation(an);
                                    playAnimation(n);
                                });
                            }
                        }
                    }
                }
            }
        };

        for (let i: number = 0; i < total; ++i) {
            const colN = (i % colNum);
            const rowN = Math.ceil((i + 1) / colNum);
            const x = colN * (spWt + gapX) + offsetX;
            const y = (rowN - 1) * (spHt + gapY);

            const spr = new MySprite();
            spr.width = spWt;
            spr.height = spHt;
            spr.x = x;
            spr.y = y;
            spr.id = i;

            sprMap[i] = {
                spr,
                val: nnArr[i],
                right: 0,
                faceFlag: true
            };

            drawFront(i);

            cardGrp.addChild(spr);
            spr.touchEnabled = true;
            spr.addEventListener(egret.TouchEvent.TOUCH_END, (evt: egret.TouchEvent) => {
                const n = evt.target.id;
                manage2Card(n);
            }, cardGrp);
        }

        for (let i: number = 0; i < total; ++i) {
            setTimeout(() => {
                playAnimation(i);
            }, 1000 + i * 20);
        }
    }

    private initCardGroup(): void {
        const { stageWidth, stageHeight } = this.stage;
        const cardGrp = new eui.Group();
        cardGrp.top = 120;
        cardGrp.bottom = 160;
        cardGrp.left = 20;
        cardGrp.right = 20;
        const grpWt = stageWidth - 40;
        const grpHt = stageHeight - 280;
        cardGrp.width = grpWt;
        cardGrp.height = grpHt;
        cardGrp.horizontalCenter = 0;
        this.cardGrp = cardGrp;
        this.addToMain(cardGrp);

        const tLayout: eui.TileLayout = new eui.TileLayout();
        tLayout.paddingTop = 20;
        tLayout.paddingLeft = 20;
        tLayout.paddingRight = 20;
        tLayout.paddingBottom = 20;
        tLayout.columnAlign = eui.ColumnAlign.JUSTIFY_USING_GAP;
        tLayout.rowAlign = eui.RowAlign.JUSTIFY_USING_GAP;
        cardGrp.layout = tLayout;

        this.drawOnCardGroup(3, 4);
    }
}
